package priv.lhy.sso.controller;

import com.google.code.kaptcha.Producer;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import priv.lhy.annotation.Anoymous;
import priv.lhy.constans.WebConstant;
import priv.lhy.utils.JwtTokenUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * author : lihy
 * date : 2019/2/12 13:55
 * 验证码生成类
 */
@Controller
@RequestMapping("captcha")
public class CaptchaController {

    @Resource
    private Producer captchaProducer;

    /**
     * 生成验证码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @Anoymous
    @RequestMapping("getCaptchaCode")
    public void getCapchaCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        //如果Header中没有定义则添加，如果已定义则用新的value覆盖原用value值
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        //如果Header中没有定义则添加，如果已定义则保持原有value不改变
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        //生成验证码文本
        String capText = captchaProducer.createText();
        System.out.println("生成的验证码文本： " + capText);
        //将验证码放入token
        Map<String, Object> payload = new HashMap<>();
        payload.put("capText", capText);
        payload.put("exp", DateTime.now().plusSeconds(WebConstant.EXP_JWT).toDate().getTime() / 1000);
        String token = JwtTokenUtils.generatorToken(payload);
        response.setHeader("Set-Cookie", "captcha_token=" + token + ";Path=/;HttpOnly");

        //生成验证码图片
        BufferedImage bufferedImage = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bufferedImage, "jpg", out);

        try {
            out.flush();
        } finally {
            out.close();
        }

    }
}
